package com.zl.zsk.config.security;

import com.zl.zsk.filter.SecurityFilter;
import com.zl.zsk.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

/**
 * @author lxb
 * @version 1.0.0
 * @desc:
 * @date 2020-03-13 9:44
 */
@Configuration
//@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserService userService;
//    @Override
//    public void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
//    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
//        http.authorizeRequests()
////                .antMatchers("/login","/failure","/static/**").permitAll()
//                .anyRequest()
//                .authenticated()
//                .and()
//                .formLogin()
////                .loginPage("/login")
////                .loginProcessingUrl("/login")
//                .failureHandler(authenticationFailureHandler()).successHandler(authenticationSuccessHandler())
//                .permitAll()
//                .and()
//                .logout()
//                .logoutSuccessHandler(logoutSuccessHandler())
////                .invalidateHttpSession(true)
////                .permitAll()
//                .and()
//                .csrf().disable();
//        http.addFilterBefore(securityFilter(),UsernamePasswordAuthenticationFilter.class);
        http.csrf().disable();
        http.exceptionHandling().authenticationEntryPoint(jwtAuthEntryPoint())
                .accessDeniedHandler(handleAccessDeny())
                .and()
                .logout().logoutUrl("/logout").logoutSuccessHandler(logoutHandler()).clearAuthentication(true).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/lxb/test").permitAll()
                .antMatchers("/user/login","/user/code/image").permitAll()
                .antMatchers("/swagger-ui.html").permitAll()
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/images/**").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/v2/api-docs").permitAll()
                .antMatchers("/configuration/ui").permitAll()
                .antMatchers("/configuration/security").permitAll()
                .anyRequest().authenticated();
        http.addFilterBefore(securityFilter(),UsernamePasswordAuthenticationFilter.class);
    }


    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        System.out.println("初始化6个0的加密密码："+passwordEncoder.encode("000000"));
        return passwordEncoder;
    }

    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public SecurityFilter securityFilter(){
        return new SecurityFilter();
    }

    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler(){
        return new HandleFailAuthentication();
    }

    @Bean
    public AuthenticationSuccessHandler authenticationSuccessHandler(){
        return new HandleSuccessAuthentication();
    }

    @Bean
    public LogoutSuccessHandler logoutSuccessHandler(){
        return new HandleLogoutSuccess();
    }

    @Bean
    public JwtAuthEntryPoint jwtAuthEntryPoint(){
        return new JwtAuthEntryPoint();
    }

    @Bean
    public HandleAccessDeny handleAccessDeny(){
        return new HandleAccessDeny();
    }

    @Bean
    public LogoutHandler logoutHandler(){
        return new LogoutHandler();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                // 设置UserDetailsService
                .userDetailsService(userService)
                // 使用BCrypt进行密码的hash
                .passwordEncoder(passwordEncoder());
    }
}
